﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CommonLibrary.DataModel.Basic;
using ServiceApplication.Service.Basic;
using OAclient.Models;
using System.Data;
using CommonLibrary.Common;
using OAclient.Common;
using ServiceApplication.Service.WorkFlow;
using System.IO;
using System.Data.OleDb;
using System.Runtime.InteropServices;
using OAclient.Filters;
using System.Configuration;

namespace OAclient.Controllers
{
    [VaildateLogin]
    [ExceptionFilter]
    [LoggerFilter]
    public class BasicController : Controller
    {
        //
        // GET: /Basic/
        BasicService bs = new BasicService();
        WorkFlowService wfs = new WorkFlowService();
        // 分页是 基本 记录数
        private const Int32 PageSize = 15;


        #region user

        public ActionResult AllUserList(Int32? page)
        {
            if (null == page) page = 1;
            //根据搜索条件返回搜索结果
            var userName = Request["userName"] ?? Request["olduserName"];
            var stime = Request["stime"] ?? Request["oldstime"];
            var etime = Request["etime"] ?? Request["oldetime"];
            var deptName = Request["deptName"] ?? Request["olddeptName"];
            var userstatus = Request["userstatus"] ?? Request["olduserstatus"];
            if (string.IsNullOrEmpty(userstatus) || userstatus != "0") userstatus = "1";//默认是在职
            ViewData["userName"] = userName;
            ViewData["stime"] = stime;
            ViewData["etime"] = etime;
            ViewData["deptName"] = deptName;
            ViewData["userstatus"] = userstatus;

            var usrEnty = new UserEntity
            {
                user_name = userName,
                dept_name = deptName,
                user_status = userstatus
            };
            var dt_user = bs.QueryUsersByCondition(usrEnty, stime, etime);

            //分页
            var pageInfo = new PagingInfo
            {
                CurrentPage = page.Value,
                ItemsPerPage = PageSize,
                TotalItems = dt_user.Rows.Count
            };

            ViewData["PagingInfo"] = pageInfo;
            if (dt_user.Rows.Count > 0)
            {
                var tmp = dt_user.AsEnumerable().Skip((page.Value - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
                ViewData["dt"] = tmp;
            }
            ViewData["dept"] = produDeptSelect();
            return View();
        }



        public ActionResult QueryUserList()
        {
            ViewData["dept"] = produDeptSelect();
            return View();
        }

        public ActionResult UserAdd()
        {
            var staff = bs.QueryNoUserStaff();
            List<SelectListItem> list_staff = new List<SelectListItem>();
            for (int i = 0; i < staff.Rows.Count; i++)
            {
                list_staff.Add(new SelectListItem
                {
                    Selected = false,
                    Text = staff.Rows[i]["员工名称"].ToString(),
                    Value = staff.Rows[i]["员工编码"].ToString(),
                });
            }

            var dept = bs.QueryAllDepts();
            var duty = bs.QueryAllDutys();
            List<SelectListItem> list_dept = new List<SelectListItem>();
            for (int i = 0; i < dept.Rows.Count; i++)
            {
                list_dept.Add(new SelectListItem
                {
                    Selected = false,
                    Text = dept.Rows[i]["部门名称"].ToString(),
                    Value = dept.Rows[i]["部门编码"].ToString(),
                });
            }
            List<SelectListItem> list_duty = new List<SelectListItem>();
            for (int i = 0; i < duty.Rows.Count; i++)
            {
                list_duty.Add(new SelectListItem
                {
                    Selected = false,
                    Text = duty.Rows[i]["职位名称"].ToString(),
                    Value = duty.Rows[i]["职位编码"].ToString(),
                });
            }

            List<SelectListItem> list_gander = new List<SelectListItem>();
            list_gander.Add(new SelectListItem
            {
                Text = "男",
                Value = "1"
            });
            list_gander.Add(new SelectListItem
            {
                Text = "女",
                Value = "2"
            });

            ViewData["list_staff"] = list_staff;
            ViewData["list_dept"] = list_dept;
            ViewData["list_duty"] = list_duty;
            ViewData["auth_id"] = produAuthSelect();
            ViewData["user_gander"] = list_gander;


            //审批权限
            var dt_spqx = wfs.WfSpqxQueryAll();
            List<SelectListItem> list_spqx = new List<SelectListItem>();
            for (int i = 0; i < dt_spqx.Rows.Count; i++)
            {
                list_spqx.Add(new SelectListItem
                {
                    Selected = false,
                    Text = dt_spqx.Rows[i]["名称"].ToString(),
                    Value = dt_spqx.Rows[i]["编码"].ToString(),
                });
            }
            ViewData["list_spqx"] = list_spqx;
            return PartialView();
        }

        static DataTable userDT = null;
        public ActionResult SortedUserList()
        {
            var userName = Request.Form["userName"];
            var stime = Request.Form["stime"];
            var etime = Request.Form["etime"];
            var deptName = Request.Form["deptName"];
            var usrEnty = new UserEntity
            {
                user_name = userName,
                dept_name = deptName
            };
            userDT = bs.QueryUsersByCondition(usrEnty, stime, etime);
            return RedirectToAction("PageUserList", new { pageIndex = 1 });
        }

        public ActionResult PageUserList(Int32 pageIndex)
        {
            var pageInfo = new PagingInfo
            {
                CurrentPage = pageIndex,
                ItemsPerPage = PageSize,
                TotalItems = userDT.Rows.Count
            };

            ViewData["PagingInfo"] = pageInfo;
            if (userDT.Rows.Count > 0)
            {
                var tmp = userDT.AsEnumerable().Skip((pageIndex - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
                ViewData["dt"] = tmp;
            }
            return View("AllUserList");
        }

        public ActionResult UserInfo(int user_id)
        {
            UserEntity ue = bs.QueryUser(user_id);
            StaffEntity se = bs.QueryStaff(ue.staff_id);
            DeptEntity de = bs.QueryDept(se.dept_id);
            DutyEntity du = bs.QueryDuty(se.duty_id);
            ViewData["dept_name"] = de.dept_name;
            ViewData["duty_name"] = du.duty_name;
            List<SelectListItem> list_status = new List<SelectListItem>();
            list_status.Add(new SelectListItem
            {
                Selected = ue.user_status == "0",
                Text = "停用",
                Value = "0"
            });
            list_status.Add(new SelectListItem
            {
                Selected = ue.user_status == "1",
                Text = "在用",
                Value = "1"
            });

            List<SelectListItem> list_znxdx = new List<SelectListItem>();
            list_znxdx.Add(new SelectListItem
            {
                Selected = ue.user_znxdx == 1,
                Text = "是",
                Value = "1"
            });
            list_znxdx.Add(new SelectListItem
            {
                Selected = ue.user_znxdx == 0,
                Text = "否",
                Value = "0"
            });

            List<SelectListItem> list_rldx = new List<SelectListItem>();
            list_rldx.Add(new SelectListItem
            {
                Selected = ue.user_rldx == 1,
                Text = "是",
                Value = "1"
            });
            list_rldx.Add(new SelectListItem
            {
                Selected = ue.user_rldx == 0,
                Text = "否",
                Value = "0"
            });

            var dt_auth = bs.QueryAllAuth();
            List<SelectListItem> list_auth = new List<SelectListItem>();
            foreach (DataRow row in dt_auth.Rows)
            {
                list_auth.Add(new SelectListItem
                {
                    Text = row["auth_name"].ToString(),
                    Value = row["auth_id"].ToString(),
                    Selected = row["auth_id"].ToString() == ue.auth_id.ToString()
                });
            }


            ViewData["list_status"] = list_status;
            ViewData["list_znxdx"] = list_znxdx;
            ViewData["list_rldx"] = list_rldx;
            ViewData["list_auth"] = list_auth;



            var dt_spqx = wfs.WfSpqxQueryAll();
            List<SelectListItem> list_spqx = new List<SelectListItem>();
            for (int i = 0; i < dt_spqx.Rows.Count; i++)
            {
                list_spqx.Add(new SelectListItem
                {
                    Selected = dt_spqx.Rows[i]["编码"].ToString() == ue.spqx_id.ToString(),
                    Text = dt_spqx.Rows[i]["名称"].ToString(),
                    Value = dt_spqx.Rows[i]["编码"].ToString(),
                });
            }
            ViewData["list_spqx"] = list_spqx;
            return PartialView(ue);
        }

        #region 方法

        public ActionResult DoUserAdd()
        {
            //var user_name = Request.Form["user_name"].ToString();
            var login_id = Request.Form["login_id"].ToString();
            var login_password = Request.Form["login_password"].ToString();
            var spqx_id = Request.Form["spqx"].ToString();
            var auth_id = Request.Form["auth_id"].ToString();
            var staff_id = Request.Form["staff_id"].ToString();
            var se = bs.QueryStaff(int.Parse(staff_id));
            //if (String.IsNullOrEmpty(user_name))
            //    return Json(new ResTag(false, "姓名不能为空"));
            if (String.IsNullOrEmpty(login_id))
                return Json(new ResTag(false, "账号不能为空"));
            if (String.IsNullOrEmpty(login_password))
                return Json(new ResTag(false, "密码不能为空"));
            if (String.IsNullOrEmpty(spqx_id))
                return Json(new ResTag(false, "请选择权限"));
            if (String.IsNullOrEmpty(auth_id))
                return Json(new ResTag(false, "请选择审批权限"));

            if (bs.QueryUserByLoginid(login_id) != null)
                return Json(new ResTag(false, "该账号已存在"));

            UserEntity user = new UserEntity()
            {
                user_name = se.staff_name,//和员工姓名绑定
                staff_id = int.Parse(staff_id),
                user_ctime = DateUtil.getStandardTimeBySecond(),
                user_loginid = login_id,
                user_psw = login_password,
                user_status = "1",
                user_lasttime = "",
                auth_id = int.Parse(auth_id),
                spqx_id = int.Parse(spqx_id)
            };
            bs.AddUser(user);
            return Json(new ResTag(true));
        }

        public ActionResult DoUserUpdate(string userid, string username, string loginid, string loginpsw, string userstatus, string usersspqx, string user_znxdx, string user_rldx, string user_auth)
        {
            if (string.IsNullOrEmpty(userid))
                return Json(new ResTag(false, "更新失败"));
            UserEntity user = bs.QueryUser(int.Parse(userid));
            user.user_name = username;
            user.user_loginid = loginid;
            user.user_psw = loginpsw;
            user.user_status = userstatus;
            user.user_znxdx = int.Parse(user_znxdx);
            user.user_rldx = int.Parse(user_rldx);
            user.spqx_id = int.Parse(usersspqx);
            user.auth_id = int.Parse(user_auth);
            if (userstatus == "0")//如果
                user.user_loginid += "fq";
            bs.UpdateUser(user);
            return Json(new ResTag(true));
        }

        public ActionResult ChangeDept(String userIds, String deptId)
        {
            if (string.IsNullOrEmpty(userIds))
                return Json(new ResTag(false, "操作失败"));
            userIds = userIds.Substring(0, userIds.Length - 1);
            bs.ChangeDept(userIds, deptId);
            return Json(new ResTag(true));
        }
        #endregion

        #endregion

        #region staff
        //staff-1
        public ActionResult AllStaffList(int? page)
        {
            if (page == null)
                page = 1;
            string staffname = Request["staffname"] ?? Request["sname"];
            string staffstime = Request["staffstime"] ?? Request["stime"];
            string staffetime = Request["staffetime"] ?? Request["etime"];
            string dept_id = Request["dept"] ?? Request["dptid"];
            string duty_id = Request["duty"] ?? Request["dtyid"];
            string staffkybz = Request["staffkybz"] ?? Request["skybz"];
            ViewData["sname"] = staffname;
            ViewData["stime"] = staffstime;
            ViewData["etime"] = staffetime;
            ViewData["dptid"] = dept_id;
            ViewData["dtyid"] = duty_id;
            ViewData["skybz"] = staffkybz;

            var dt_staff = bs.QueryAllStaff();


            string str_filter = string.Format("员工名称 like '%{0}%' ", staffname);
            if (!string.IsNullOrEmpty(staffstime))
            {
                staffstime = DateUtil.getBeginTimeBySecond(DateTime.Parse(staffstime));
                str_filter += " and 创建时间>='" + staffstime + "'";
            }
            if (!string.IsNullOrEmpty(staffstime))
            {
                staffetime = DateUtil.getEndTimeBySecond(DateTime.Parse(staffetime));
                str_filter += " and 创建时间<='" + staffetime + "'";
            }
            if (!string.IsNullOrEmpty(dept_id))
            {
                str_filter += " and 部门编码='" + dept_id + "'";
            }
            if (!string.IsNullOrEmpty(duty_id))
            {
                str_filter += " and 职位编码='" + duty_id + "'";
            }
            if (!string.IsNullOrEmpty(staffkybz))
            {
                str_filter += " and 在职标志='" + staffkybz + "'";
            }
            else//默认搜索在职
            {
                str_filter += " and 在职标志='在职' ";
            }
            var drs_res = dt_staff.Select(str_filter);
            var newdt = dt_staff.Clone();
            for (int i = 0; i < drs_res.Length; i++)
            {
                newdt.ImportRow((DataRow)drs_res[i]);
            }

            if (newdt.Rows.Count > 0)
            {
                var tmp = newdt.AsEnumerable().Skip((page.Value - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
                ViewData["dt"] = tmp;
            }

            //分页
            var pageInfo = new PagingInfo
            {
                CurrentPage = page.Value,
                ItemsPerPage = PageSize,
                TotalItems = newdt.Rows.Count
            };

            ViewData["PagingInfo"] = pageInfo;

            var dept = bs.QueryAllDepts();
            var duty = bs.QueryAllDutys();
            List<SelectListItem> list_dept = new List<SelectListItem>();
            for (int i = 0; i < dept.Rows.Count; i++)
            {
                list_dept.Add(new SelectListItem
                {
                    Selected = false,
                    Text = dept.Rows[i]["部门名称"].ToString(),
                    Value = dept.Rows[i]["部门编码"].ToString(),
                });
            }
            List<SelectListItem> list_duty = new List<SelectListItem>();
            for (int i = 0; i < duty.Rows.Count; i++)
            {
                list_duty.Add(new SelectListItem
                {
                    Selected = false,
                    Text = duty.Rows[i]["职位名称"].ToString(),
                    Value = duty.Rows[i]["职位编码"].ToString(),
                });
            }

            ViewData["list_dept"] = list_dept;
            ViewData["list_duty"] = list_duty;
            return View();
        }

        //staff-1-1
        public ActionResult StaffInfo(string staff_id)
        {

            var dept = bs.QueryAllDepts();
            var duty = bs.QueryAllDutys();
            List<SelectListItem> list_dept = new List<SelectListItem>();
            for (int i = 0; i < dept.Rows.Count; i++)
            {
                list_dept.Add(new SelectListItem
                {
                    Selected = false,
                    Text = dept.Rows[i]["部门名称"].ToString(),
                    Value = dept.Rows[i]["部门编码"].ToString(),
                });
            }
            List<SelectListItem> list_duty = new List<SelectListItem>();
            for (int i = 0; i < duty.Rows.Count; i++)
            {
                list_duty.Add(new SelectListItem
                {
                    Selected = false,
                    Text = duty.Rows[i]["职位名称"].ToString(),
                    Value = duty.Rows[i]["职位编码"].ToString(),
                });
            }

            List<SelectListItem> list_sex = new List<SelectListItem>();
            list_sex.Add(new SelectListItem
            {
                Selected = false,
                Text = "男",
                Value = "1"
            });
            list_sex.Add(new SelectListItem
            {
                Selected = false,
                Text = "女",
                Value = "2"
            });

            List<SelectListItem> list_kybz = new List<SelectListItem>();
            list_kybz.Add(new SelectListItem
            {
                Selected = false,
                Text = "在职",
                Value = "在职"
            });
            list_kybz.Add(new SelectListItem
            {
                Selected = false,
                Text = "离职",
                Value = "离职"
            });
            ViewData["list_dept"] = list_dept;
            ViewData["list_duty"] = list_duty;
            ViewData["auth_id"] = produAuthSelect();
            ViewData["list_sex"] = list_sex;
            ViewData["list_kybz"] = list_kybz;

            if (!string.IsNullOrEmpty(staff_id))
            {
                var staffEntity = bs.QueryStaff(int.Parse(staff_id));
                var deptEntity = bs.QueryDept(staffEntity.dept_id);
                var dutyEntity = bs.QueryDuty(staffEntity.duty_id);
                list_dept.Where(x => x.Text == deptEntity.dept_name).First().Selected = true;
                list_duty.Where(x => x.Text == dutyEntity.duty_name).First().Selected = true;
                list_sex.Where(x => x.Value == staffEntity.staff_sex).First().Selected = true;
                list_kybz.Where(x => x.Text == staffEntity.staff_kybz).First().Selected = true;

                if (staffEntity != null)
                {
                    ViewData["staff_id"] = staffEntity.staff_id;
                    ViewData["staff_name"] = staffEntity.staff_name;
                    ViewData["dept_id"] = staffEntity.dept_id;
                    ViewData["dept_name"] = deptEntity.dept_name;
                    ViewData["duty_id"] = staffEntity.duty_id;
                    ViewData["duty_name"] = dutyEntity.duty_name;
                    ViewData["staff_sex"] = staffEntity.staff_sex;
                    ViewData["staff_homeaddr"] = staffEntity.staff_homeaddr;
                    ViewData["staff_img"] = staffEntity.staff_img;
                    ViewData["staff_sfz"] = staffEntity.staff_sfz;
                    ViewData["staff_postnum"] = staffEntity.staff_postnum;
                    ViewData["staff_marrige"] = staffEntity.staff_marrige;
                    ViewData["staff_study"] = staffEntity.staff_study;
                    ViewData["staff_school"] = staffEntity.staff_school;
                    ViewData["staff_major"] = staffEntity.staff_major;
                    ViewData["staff_politics"] = staffEntity.staff_politics;
                    ViewData["staff_birth"] = staffEntity.staff_birth;
                    ViewData["staff_interest"] = staffEntity.staff_interest;
                    ViewData["staff_zybl"] = staffEntity.staff_zybl;
                    ViewData["staff_liveaddr"] = staffEntity.staff_liveaddr;
                    ViewData["staff_livenum"] = staffEntity.staff_livenum;
                    ViewData["staff_mobile"] = staffEntity.staff_mobile;
                    ViewData["staff_shortnum"] = staffEntity.staff_shortnum;
                    ViewData["staff_officenum"] = staffEntity.staff_officenum;
                    ViewData["staff_officeaddr"] = staffEntity.staff_officeaddr;
                    ViewData["staff_rzsj"] = staffEntity.staff_rzsj;
                    ViewData["staff_lxr"] = staffEntity.staff_lxr;
                    ViewData["staff_lxrphone"] = staffEntity.staff_lxrphone;
                    ViewData["staff_jsr"] = staffEntity.staff_jsr;
                    ViewData["staff_gzjl"] = staffEntity.staff_gzjl;
                    ViewData["staff_jtcy"] = staffEntity.staff_jtcy;
                    ViewData["staff_email"] = staffEntity.staff_email;
                    ViewData["staff_qq"] = staffEntity.staff_qq;
                    ViewData["staff_fax"] = staffEntity.staff_fax;
                    ViewData["staff_height"] = staffEntity.staff_height;
                    ViewData["staff_nation"] = staffEntity.staff_nation;
                    ViewData["staff_sygz"] = staffEntity.staff_sygz;
                    ViewData["staff_zzgz"] = staffEntity.staff_zzgz;
                    ViewData["staff_sfsb"] = staffEntity.staff_sfsb;
                    ViewData["staff_code"] = staffEntity.staff_code;
                    ViewData["staff_descn"] = staffEntity.staff_descn;
                    ViewData["staff_ctime"] = staffEntity.staff_ctime;
                    ViewData["staff_fjh"] = staffEntity.staff_fjh;
                    ViewData["staff_erp"] = staffEntity.staff_erp;
                    ViewData["staff_empsw"] = staffEntity.staff_empsw;
                    ViewData["staff_kybz"] = staffEntity.staff_kybz;
                }
            }
            return View();
        }

        public ActionResult ImportStaff()
        {
            string failmsg = string.Empty;
            foreach (String upload in Request.Files)
            {
                if (Request.Files[upload] != null)
                {
                    var fileData = Request.Files[upload];
                    try
                    {
                        var fileName = fileData.FileName;
                        var ext = Path.GetExtension(fileName);
                        if (ext != ".xls")
                            return Content("ext_fail");

                        var filePath = Server.MapPath("~/Temp");
                        if (!Directory.Exists(filePath))
                            Directory.CreateDirectory(filePath);

                        var fullName = Path.Combine(filePath, fileName);
                        fileData.SaveAs(fullName);

                        var dt = new DataTable();
                        String strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Excel 8.0; data source=" + fullName;
                        OleDbConnection myConn = new OleDbConnection(strCon);
                        string strCom = " SELECT * FROM [Sheet1$]";
                        myConn.Open();
                        OleDbDataAdapter myCommand = new OleDbDataAdapter(strCom, myConn);
                        myCommand.Fill(dt);
                        myConn.Close();

                        var rowCount = dt.Rows.Count - 1;
                        var colCount = dt.Columns.Count;
                        for (int rowIndex = 1; rowIndex < rowCount; rowIndex++)
                        {
                            var staffEntity = new StaffEntity
                            {
                                staff_id = Int32.Parse(dt.Rows[rowIndex][0].ToString()),
                                staff_name = dt.Rows[rowIndex][1].ToString(),
                                dept_id = Int32.Parse(dt.Rows[rowIndex][2].ToString()),
                                duty_id = Int32.Parse(dt.Rows[rowIndex][4].ToString()),
                                staff_sex = dt.Rows[rowIndex][6].ToString(),
                                staff_homeaddr = dt.Rows[rowIndex][7].ToString(),
                                staff_img = dt.Rows[rowIndex][8].ToString(),
                                staff_sfz = dt.Rows[rowIndex][9].ToString(),
                                staff_postnum = dt.Rows[rowIndex][10].ToString(),
                                staff_marrige = dt.Rows[rowIndex][11].ToString(),
                                staff_study = dt.Rows[rowIndex][12].ToString(),
                                staff_school = dt.Rows[rowIndex][13].ToString(),
                                staff_major = dt.Rows[rowIndex][14].ToString(),
                                staff_politics = dt.Rows[rowIndex][15].ToString(),
                                staff_birth = dt.Rows[rowIndex][16].ToString(),
                                staff_interest = dt.Rows[rowIndex][17].ToString(),
                                staff_zybl = dt.Rows[rowIndex][18].ToString(),
                                staff_liveaddr = dt.Rows[rowIndex][19].ToString(),
                                staff_mobile = dt.Rows[rowIndex][20].ToString(),
                                staff_shortnum = dt.Rows[rowIndex][21].ToString(),
                                staff_officenum = dt.Rows[rowIndex][22].ToString(),
                                staff_rzsj = dt.Rows[rowIndex][23].ToString(),
                                staff_lxr = dt.Rows[rowIndex][24].ToString(),
                                staff_lxrphone = dt.Rows[rowIndex][25].ToString(),
                                staff_jsr = dt.Rows[rowIndex][26].ToString(),
                                staff_gzjl = dt.Rows[rowIndex][27].ToString(),
                                staff_jtcy = dt.Rows[rowIndex][28].ToString(),
                                staff_email = dt.Rows[rowIndex][29].ToString(),
                                staff_qq = dt.Rows[rowIndex][30].ToString(),
                                staff_fax = dt.Rows[rowIndex][31].ToString(),
                                staff_height = dt.Rows[rowIndex][32].ToString(),
                                staff_nation = dt.Rows[rowIndex][33].ToString(),
                                staff_sygz = decimal.Parse(dt.Rows[rowIndex][34].ToString()),
                                staff_zzgz = decimal.Parse(dt.Rows[rowIndex][35].ToString()),
                                staff_sfsb = dt.Rows[rowIndex][36].ToString(),
                                staff_code = dt.Rows[rowIndex][37].ToString(),
                                staff_descn = dt.Rows[rowIndex][38].ToString(),
                                staff_ctime = dt.Rows[rowIndex][39].ToString(),
                                staff_officeaddr = dt.Rows[rowIndex][40].ToString(),
                                staff_fjh = dt.Rows[rowIndex][41].ToString(),// 新增 mlh 2012-08-28
                                staff_erp = dt.Rows[rowIndex][42].ToString(),// 新增 mlh 2012-08-28
                                staff_empsw = dt.Rows[rowIndex][43].ToString(),// 新增 mlh 2012-08-28
                                staff_livenum = dt.Rows[rowIndex][44].ToString(),// 新增 mlh 2012-08-28
                                staff_kybz = "在职"// 新增 mlh 2012-08-28
                            };

                            if (bs.QueryStaff(staffEntity.staff_name) != null || string.IsNullOrEmpty(staffEntity.staff_name))
                            {
                                failmsg += staffEntity.staff_name + " ";
                                continue;
                            }
                            else
                                bs.AddStaff(staffEntity);
                        }
                    }
                    catch
                    {
                        return Json(new ResTag(false, "上传出错"));
                    }
                }
            }
            if (string.IsNullOrEmpty(failmsg))
                return Json(new ResTag(true));
            else
                return Json(new ResTag(false, "以下名字已存在:" + failmsg));
        }

        public FileResult DeriveStaff()
        {
            Microsoft.Office.Interop.Excel.Application xlsApp = null;
            Microsoft.Office.Interop.Excel._Workbook xlsBook = null;
            Microsoft.Office.Interop.Excel._Worksheet xlsSheet = null;

            try
            {
                xlsApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
                xlsBook = xlsApp.Workbooks.Add(true);
                xlsSheet = (Microsoft.Office.Interop.Excel._Worksheet)xlsBook.ActiveSheet;
                var dt = bs.QueryAllStaff();
                var colCount = dt.Columns.Count;
                var rowCount = dt.Rows.Count;
                for (int colIndex = 0; colIndex < colCount; colIndex++)
                {
                    xlsApp.Cells[1, colIndex + 1] = dt.Columns[colIndex].Caption;
                }
                for (int rowIndex = 0; rowIndex < rowCount; rowIndex++)
                {
                    for (int colIndex = 0; colIndex < colCount; colIndex++)
                    {
                        xlsApp.Cells[rowIndex + 2, colIndex + 1] = dt.Rows[rowIndex][colIndex].ToString();
                    }
                }

                var filePath = Server.MapPath("~/Temp/");
                if (!Directory.Exists(filePath))
                    Directory.CreateDirectory(filePath);

                xlsApp.Visible = false;
                xlsApp.DisplayAlerts = false;
                xlsApp.ActiveWorkbook.SaveAs(filePath + "员工表.xls", Microsoft.Office.Interop.Excel.XlFileFormat.xlTemplate,
                    null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
                xlsBook.Saved = true;
                xlsApp.Workbooks.Close();
                xlsApp.Quit();
                Marshal.ReleaseComObject((Object)xlsSheet);
                xlsSheet = null;
                Marshal.ReleaseComObject((Object)xlsBook);
                xlsBook = null;
                Marshal.ReleaseComObject((Object)xlsApp);
                xlsApp = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();

                return File(new FileStream(filePath + "员工表.xls", FileMode.Open), "application/octet-stream", "员工表.xls");
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
            return null;
        }

        #region 方法

        public ActionResult DoStaffAddOrUpdate()
        {
            StaffEntity staffEntity = new StaffEntity();

            staffEntity.staff_name = Request.Form["staff_name"].ToString();
            staffEntity.dept_id = int.Parse(Request.Form["dept_id"].ToString());
            staffEntity.duty_id = int.Parse(Request.Form["duty_id"].ToString());
            staffEntity.staff_sex = Request.Form["staff_sex"].ToString();
            staffEntity.staff_homeaddr = Request.Form["staff_homeaddr"].ToString();
            staffEntity.staff_img = "";
            staffEntity.staff_sfz = Request.Form["staff_sfz"].ToString();
            staffEntity.staff_postnum = Request.Form["staff_postnum"].ToString();
            staffEntity.staff_marrige = Request.Form["staff_marrige"].ToString();
            staffEntity.staff_study = Request.Form["staff_study"].ToString();
            staffEntity.staff_school = Request.Form["staff_school"].ToString();
            staffEntity.staff_major = Request.Form["staff_major"].ToString();
            staffEntity.staff_politics = Request.Form["staff_politics"].ToString();
            staffEntity.staff_birth = Request.Form["staff_birth"].ToString();
            staffEntity.staff_interest = Request.Form["staff_interest"].ToString();
            staffEntity.staff_zybl = Request.Form["staff_zybl"].ToString();
            staffEntity.staff_liveaddr = Request.Form["staff_liveaddr"].ToString();
            staffEntity.staff_livenum = Request.Form["staff_livenum"].ToString();
            staffEntity.staff_mobile = Request.Form["staff_mobile"].ToString();
            staffEntity.staff_shortnum = Request.Form["staff_shortnum"].ToString();
            staffEntity.staff_officenum = Request.Form["staff_officenum"].ToString();
            staffEntity.staff_rzsj = Request.Form["staff_rzsj"].ToString();
            staffEntity.staff_lxr = Request.Form["staff_lxr"].ToString();
            staffEntity.staff_lxrphone = Request.Form["staff_lxrphone"].ToString();
            staffEntity.staff_jsr = Request.Form["staff_jsr"].ToString();
            staffEntity.staff_gzjl = Request.Form["staff_gzjl"].ToString();
            staffEntity.staff_jtcy = Request.Form["staff_jtcy"].ToString();
            staffEntity.staff_email = Request.Form["staff_email"].ToString();
            staffEntity.staff_qq = Request.Form["staff_qq"].ToString();
            staffEntity.staff_fax = Request.Form["staff_fax"].ToString();
            staffEntity.staff_height = Request.Form["staff_height"].ToString();
            staffEntity.staff_nation = Request.Form["staff_nation"].ToString();
            staffEntity.staff_sygz = decimal.Parse(Request.Form["staff_sygz"].ToString() == "" ? "0" : Request.Form["staff_sygz"].ToString());
            staffEntity.staff_zzgz = decimal.Parse(Request.Form["staff_zzgz"].ToString() == "" ? "0" : Request.Form["staff_zzgz"].ToString());
            staffEntity.staff_sfsb = Request.Form["staff_sfsb"].ToString();
            staffEntity.staff_code = Request.Form["staff_code"].ToString();
            staffEntity.staff_descn = Request.Form["staff_descn"].ToString();
            staffEntity.staff_ctime = Request.Form["staff_ctime"].ToString();
            staffEntity.staff_officeaddr = Request.Form["staff_officeaddr"].ToString();
            staffEntity.staff_fjh = Request.Form["staff_fjh"].ToString();
            staffEntity.staff_erp = Request.Form["staff_erp"].ToString();
            staffEntity.staff_empsw = Request.Form["staff_empsw"].ToString();
            staffEntity.staff_kybz = Request.Form["staff_kybz"].ToString();
            var staff_id = Request.Form["staff_id"] == null ? "" : Request.Form["staff_id"].ToString();

            if (string.IsNullOrEmpty(staff_id))
            {
                if (bs.QueryStaff(staffEntity.staff_name) != null)
                    return Json(new ResTag(false, "已存在该姓名员工"));
                bs.AddStaff(staffEntity);
            }
            else
            {
                var tmp = bs.QueryStaff(int.Parse(staff_id));
                if (tmp != null)
                {
                    staffEntity.staff_id = int.Parse(staff_id);
                    bs.UpdateStaff(staffEntity);
                }
                else
                {
                    return Json(new ResTag(false, "更新失败"));
                }
            }

            return Json(new ResTag(true));
        }

        #endregion
        #endregion

        #region dept

        public ActionResult AllDeptList(Int32? page)
        {
            if (null == page) page = 1;

            var dt_dept = bs.QueryAllDepts();
            //分页
            var pageInfo = new PagingInfo
            {
                CurrentPage = page.Value,
                ItemsPerPage = PageSize,
                TotalItems = dt_dept.Rows.Count
            };

            ViewData["PagingInfo"] = pageInfo;
            if (dt_dept.Rows.Count > 0)
            {
                var tmp = dt_dept.AsEnumerable().Skip((page.Value - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
                ViewData["dt"] = tmp;
            }

            return PartialView();
        }

        public ActionResult CheckDept()
        {
            var node = ZTreeHelper.Serialize(bs.GetDeptNodes());
            ViewData["pardept"] = node;

            ViewData["operType"] = "check";
            return View();
        }

        public ActionResult UpdateDept()
        {
            var node = ZTreeHelper.Serialize(bs.GetDeptNodes());

            ViewData["pardept"] = node;
            ViewData["operType"] = "update";
            return View("CheckDept");
        }

        [HttpPost]
        public ActionResult UpdateDept(FormCollection collect)
        {
            var pardept = collect["pardept"].ToString();
            var deptName = collect["deptName"].ToString();
            var deptCatal = collect["deptCatal"].ToString();
            var deptDescn = collect["deptDescn"].ToString();
            var deptId = collect["deptId"].ToString();

            if (String.IsNullOrEmpty(deptName))
                return Json(new ResTag(false, "部门名称不能为空"));

            ViewData["operType"] = "update";

            // 跟部门不让其修改
            if (deptId != pardept)
            {
                var parDepart = bs.QueryDept(Convert.ToInt32(pardept));
                var deptEntity = new DeptEntity
                {
                    dept_id = Convert.ToInt32(deptId),
                    dept_supid = Convert.ToInt32(pardept),
                    dept_longid = pardept == "1" ? parDepart.dept_longid : parDepart.dept_longid + pardept + "!",
                    dept_name = deptName,
                    dept_catalogy = deptCatal,
                    dept_descn = deptDescn,
                    dept_isroot = pardept == "1" ? 1 : 0,
                    dept_isfather = 0,
                    dept_status = "1"
                };
                bs.UpdateDept(deptEntity);
            }
            var node = ZTreeHelper.Serialize(bs.GetDeptNodes());
            ViewData["pardept"] = node;
            return Json(new ResTag(true));
        }

        public ActionResult DeptDetail(String deptId, String operType)
        {
            var dept = bs.QueryDept(Convert.ToInt32(deptId));
            var supid = dept.dept_id == 1 ? 1 : dept.dept_supid;
            ViewData["supdept"] = bs.QueryDept(supid).dept_name;
            ViewData["deptName"] = dept.dept_name;
            ViewData["deptCatal"] = dept.dept_catalogy;
            ViewData["deptDescn"] = dept.dept_descn;
            if (deptId == "1")
                operType = "check";
            ViewData["operType"] = operType;
            if (operType == "update")
            {
                ViewData["deptId"] = deptId;
                ViewData["pardept"] = produDeptSelect(supid.ToString(), bs.QueryDept(Convert.ToInt32(supid)).dept_name);
            }

            return View();
        }

        public ActionResult DeptInfo(string deptid)
        {
            var dept = bs.QueryDept(Convert.ToInt32(deptid));
            var supid = dept.dept_id == 1 ? 1 : dept.dept_supid;
            ViewData["supdept"] = bs.QueryDept(supid).dept_name;
            ViewData["deptName"] = dept.dept_name;
            ViewData["deptCatal"] = dept.dept_catalogy;
            ViewData["deptDescn"] = dept.dept_descn;

            ViewData["deptId"] = deptid;
            ViewData["pardept"] = produDeptSelect(supid.ToString(), bs.QueryDept(Convert.ToInt32(supid)).dept_name);


            return View();
        }

        public ActionResult AddDept()
        {
            var node = ZTreeHelper.Serialize(bs.GetDeptNodes());
            ViewData["pardeptList"] = produDeptSelect();
            ViewData["pardept"] = node;
            return View();
        }

        [HttpPost]
        public ActionResult AddDept(FormCollection collects)
        {
            var pardept = collects["pardeptList"].ToString();
            var deptName = collects["deptName"].ToString();
            var deptCatal = collects["deptCatal"].ToString();
            var deptDescn = collects["deptDescn"].ToString();

            if (String.IsNullOrEmpty(deptName))
                return JavaScript("alert('部门名称不能为空')");


            var parDepart = bs.QueryDept(Convert.ToInt32(pardept));
            var deptEntity = new DeptEntity
            {
                dept_supid = Convert.ToInt32(pardept),
                dept_longid = pardept == "1" ? parDepart.dept_longid : parDepart.dept_longid + pardept + "!",
                dept_name = deptName,
                dept_catalogy = deptCatal,
                dept_descn = deptDescn,
                dept_isroot = pardept == "1" ? 1 : 0,
                dept_isfather = 0,
                dept_status = "1"
            };
            bs.AddDept(deptEntity);
            ViewData["pardeptList"] = produDeptSelect();
            var node = ZTreeHelper.Serialize(bs.GetDeptNodes());
            ViewData["pardept"] = node;
            return View();
        }

        private List<SelectListItem> produDeptSelect()
        {
            return produDeptSelect(null, null);
        }

        private List<SelectListItem> produDeptSelect(String deptId, String deptName)
        {

            List<SelectListItem> select = new List<SelectListItem>();
            var depts = produDeptTable(deptId, deptName);

            foreach (DataRow dept in depts.Rows)
            {
                select.Add(new SelectListItem
                {
                    Text = dept["部门名称"].ToString(),
                    Value = dept["部门编码"].ToString()
                });
            }

            return select;
        }

        private DataTable produDeptTable(String deptId, String deptName)
        {
            var depts = bs.QueryAllDepts();
            if (String.IsNullOrEmpty(deptId) || String.IsNullOrEmpty(deptName))
                return depts;

            var deptDt = new DataTable();
            deptDt.Columns.Add("部门名称");
            deptDt.Columns.Add("部门编码");

            DataRow newRow = deptDt.NewRow();

            newRow["部门名称"] = deptName;
            newRow["部门编码"] = deptId;
            deptDt.Rows.Add(newRow);
            foreach (DataRow row in depts.Rows)
            {
                if (deptId != row["部门编码"].ToString())
                {
                    newRow = deptDt.NewRow();
                    newRow["部门名称"] = row["部门名称"];
                    newRow["部门编码"] = row["部门编码"];
                    deptDt.Rows.Add(newRow);
                }
            }

            return deptDt;

        }

        #region 方法
        public ActionResult DoUpdateDept(string deptId, string pdeptId, string deptName, string deptCatal, string deptDescn)
        {
            //var pardept = collect["pardept"].ToString();
            //var deptName = collect["deptName"].ToString();
            //var deptCatal = collect["deptCatal"].ToString();
            //var deptDescn = collect["deptDescn"].ToString();
            //var deptId = collect["deptId"].ToString();

            if (String.IsNullOrEmpty(deptName))
                return Json(new ResTag(false, "部门名称不能为空"));
            if (deptId == pdeptId)
                return Json(new ResTag(false, "无法修改跟部门"));

            var parDepart = bs.QueryDept(Convert.ToInt32(pdeptId));
            var deptEntity = new DeptEntity
            {
                dept_id = Convert.ToInt32(deptId),
                dept_supid = Convert.ToInt32(pdeptId),
                dept_longid = pdeptId == "1" ? parDepart.dept_longid : parDepart.dept_longid + pdeptId + "!",
                dept_name = deptName,
                dept_catalogy = deptCatal,
                dept_descn = deptDescn,
                dept_isroot = pdeptId == "1" ? 1 : 0,
                dept_isfather = 0,
                dept_status = "1"
            };
            bs.UpdateDept(deptEntity);

            return Json(new ResTag(true));
        }

        public ActionResult DoDeptAdd(string pardeptList, string deptName, string deptCatal, string deptDescn)
        {
            var pardept = pardeptList;
            //var pardept = collects["pardeptList"].ToString();
            //var deptName = collects["deptName"].ToString();
            //var deptCatal = collects["deptCatal"].ToString();
            //var deptDescn = collects["deptDescn"].ToString();

            if (String.IsNullOrEmpty(deptName))
                return Json(new ResTag(false, "部门名称不能为空"));

            if (bs.QueryDept(deptName) != null)
                return Json(new ResTag(false, "该部门已存在"));

            var parDepart = bs.QueryDept(Convert.ToInt32(pardept));
            var deptEntity = new DeptEntity
            {
                dept_supid = Convert.ToInt32(pardept),
                dept_longid = pardept == "1" ? parDepart.dept_longid : parDepart.dept_longid + pardept + "!",
                dept_name = deptName,
                dept_catalogy = deptCatal,
                dept_descn = deptDescn,
                dept_isroot = pardept == "1" ? 1 : 0,
                dept_isfather = 0,
                dept_status = "1"
            };
            bs.AddDept(deptEntity);

            return Json(new ResTag(true));
        }
        #endregion
        #endregion

        #region duty

        public ActionResult AllDutyList(Int32? page)
        {
            if (page == null) page = 1;
            var duty = bs.QueryAllDutys();
            var pageInfo = new PagingInfo
            {
                CurrentPage = page.Value,
                ItemsPerPage = PageSize,
                TotalItems = duty.Rows.Count
            };
            ViewData["pageInfo"] = pageInfo;

            if (duty.Rows.Count > 0)
                duty = duty.AsEnumerable().Skip((page.Value - 1) * PageSize).Take(PageSize).CopyToDataTable<DataRow>();
            ViewData["dt"] = duty;
            return PartialView();
        }

        public ActionResult DutyAddOrUpdate(string duty_id)
        {
            if (!string.IsNullOrEmpty(duty_id))
            {
                var duty = bs.QueryDuty(int.Parse(duty_id));
                ViewData["duty_id"] = duty.duty_id;
                ViewData["duty_name"] = duty.duty_name;
                ViewData["duty_descn"] = duty.duty_descn;
            }

            ViewData["dept_list"] = produDeptSelect();


            return View();
        }


        [HttpPost]
        public ActionResult AddDuty(FormCollection collect)
        {
            var duty_name = collect["duty_name"].ToString();
            var duty_desn = collect["duty_desn"].ToString();
            var dept = collect["dept_list"].ToString();
            var dutyEntity = new DutyEntity
            {
                dept_id = Convert.ToInt32(dept),
                duty_descn = duty_desn,
                duty_name = duty_name,
                duty_lev = 1
            };
            bs.AddDuty(dutyEntity);

            ViewData["dept_list"] = produDeptSelect();
            return View();
        }

        private List<SelectListItem> produAuthSelect()
        {
            //var duty = bs.QueryAllDutys();
            //List<SelectListItem> select = new List<SelectListItem>();
            //foreach (DataRow row in duty.Rows)
            //{
            //    select.Add(new SelectListItem
            //    {
            //        Text = row["职位名称"].ToString(),
            //        Value = row["职位编码"].ToString()
            //    });
            //}

            //mlh 2012-10-29 auth的数据源应该是user_auth表里的东西
            var auth = bs.QueryAllAuth();
            List<SelectListItem> select = new List<SelectListItem>();
            foreach (DataRow row in auth.Rows)
            {
                select.Add(new SelectListItem
                {
                    Text = row["auth_name"].ToString(),
                    Value = row["auth_id"].ToString()
                });
            }

            return select;
        }


        #region 方法

        public ActionResult DoDutyAddOrUpdate(FormCollection collect)
        {
            var duty_id = collect["duty_id"].ToString();
            var duty_name = collect["duty_name"].ToString();
            var duty_desn = collect["duty_desn"].ToString();
            //var dept = collect["dept_list"].ToString();
            if (string.IsNullOrEmpty(duty_name))
                return Json(new ResTag(false, "请输入职务名称"));


            var dutyEntity = new DutyEntity
            {
                //dept_id = Convert.ToInt32(dept),
                duty_descn = duty_desn,
                duty_name = duty_name,
                duty_lev = 1
            };
            if (string.IsNullOrEmpty(duty_id))
            {
                if (bs.QueryDuty(duty_name) != null)
                    return Json(new ResTag(false, "该职位已存在"));
                bs.AddDuty(dutyEntity);
            }
            else
                bs.UpdateDuty(dutyEntity);

            return Json(new ResTag(true));
        }

        #endregion
        #endregion

        public ActionResult GetImage(String fileName)
        {
            string mime = FileHelper.GetFileMIME(Path.GetExtension(fileName));
            String filePath = Path.Combine(ComVariable.StoreUrl, fileName);

            return File(new FileStream(filePath, FileMode.Open, FileAccess.Read), mime, fileName);
        }


    }
}
